package com.netintech.intelligenceInterface.common.interceptor;

import com.netintech.intelligenceInterface.common.Type;
import com.netintech.intelligenceInterface.common.customException.InterfaceCallException;
import com.netintech.intelligenceInterface.iflytek.util.AuthenticationUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

import static com.netintech.intelligenceInterface.common.StaticBean.*;
import static com.netintech.intelligenceInterface.common.Type.AUTH_FAILED;

/**
 * @author lining
 * @date 2021/4/30 15:29
 */
@Component
public class AuthInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String date = request.getHeader("date");
        String host = request.getHeader("host");
        String authorization = request.getHeader("authorization");
        if (StringUtils.isEmpty(date)) {
            throw new InterfaceCallException(Type.MISS_PARAM, TIME_MISS);
        }
        if (StringUtils.isEmpty(host)) {
            throw new InterfaceCallException(Type.MISS_PARAM, HOST_MISS);
        }
        if (StringUtils.isEmpty(authorization)) {
            throw new InterfaceCallException(Type.MISS_PARAM, AUTHORIZATION_MISS);
        }
        Map<String, String> map = new HashMap<>();
        map.put("authorization", authorization);
        map.put("date", date);
        map.put("host", host);
        if (!AuthenticationUtil.authentication(request.getMethod(), request.getRequestURL().toString(), map)) {
            throw new InterfaceCallException(AUTH_FAILED, AUTHORIZATION_FAILED);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {

    }
}
